import React from 'react';
import { Select } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { fetchSocialSecurityCityList } from '../services';

const { Option } = Select;

const SocialSecurityCity = React.forwardRef(({ value, onChange }, ref) => {
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    const { administrativeOrganizationCode } = user;

    const { data: city } = useRequest(() => fetchSocialSecurityCityList(administrativeOrganizationCode), {
        ...defaultFormatResult
    });

    const handleChanged = selectCity => {
        if (onChange) {
            const result = city.find(item => item.socialCityCode === selectCity) || {};
            onChange({ socialCityCode: selectCity, socialCityName: result.socialCityName || '' });
        }
    };

    return (
        <Select
            placeholder="请选择"
            ref={ref}
            value={value ? value?.socialCityCode : undefined}
            onChange={handleChanged}
        >
            {Array.isArray(city) &&
                city.map(item => {
                    const { socialCityCode, socialCityNamePath, id } = item;
                    return (
                        <Option key={id} value={socialCityCode}>
                            {socialCityNamePath}
                        </Option>
                    );
                })}
        </Select>
    );
});

export default SocialSecurityCity;
